package com.gkd.controller.regular;

import com.gkd.constant.MessageConstant;
import com.gkd.properties.UploadProperties;
import com.gkd.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController("regularCommonController")
@Slf4j
@CrossOrigin
@RequestMapping("/regular/common")
public class CommonController {

    @Autowired
    private UploadProperties uploadProperties;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传");
        try{
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取原始文件的后缀 .xxx
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //用uuid拼接文件名
            String objectName = UUID.randomUUID().toString() + extension;

            //创建文件存储路径
            File dir = new File(uploadProperties.getDirectory());
            if (!dir.exists()){
                dir.mkdir();
            }
            //存储到本地
            file.transferTo(new File(dir.getAbsolutePath(),objectName));
            //前端访问路径
            String path = "http://"+uploadProperties.getHost()+":"+uploadProperties.getPort()+"/upload/" + objectName;
            //返回数据
            log.info("图片路径:"+path);
            return Result.success(path);
        }catch (Exception e){
            log.error(e.getMessage());
            log.error(MessageConstant.UPLOAD_FAILED);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
